package ltd.followkba.page;

import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.view.View;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import ltd.advskin.C;
import ltd.advskin.MRAM;
import ltd.advskin.MSKIN;
import ltd.advskin.base.BaseList;
import ltd.advskin.base.KcListHolder;
import ltd.advskin.base.KcListListener;

import ltd.advskin.base.KcNoneListener;
import ltd.advskin.base.KcTypeListener;
import ltd.advskin.view.KcHeaderView;
import ltd.advskin.view.KcListView;

import ltd.followkba.MAPP;
import ltd.followkba.MDBS;
import ltd.followkba.R;
import ltd.followkba.comment.bean.BUsage;
import ltd.followkba.task.FreeType;
import main.MAPI;

import static ltd.advskin.MSKIN.MSTRING;



public class RunStatePage extends BaseList {
    private List<BUsage>[] mBUsage;


    // 所有的页面都接受同样的方式打开LOG
    public static boolean logEnable;
    public void MLOG(String text) {
        if (logEnable) {
            MSTRING(MAPI.GET_LOG_NAME(this) + text);
        }
    }
    @Override
    public void onInitView() {                       // 使用者需要继承，初始化页面控件等显示
        setLayout(R.layout.page_simple_list);
        mKcHeaderView = (KcHeaderView) findViewById(R.id.khvSimpleList);
        mKcHeaderView.setRight(C.clear, null);
        mKcHeaderView.setTitle("APP's 运行状态", new KcTypeListener() {
            @Override
            public void onMessage(int type) {
                switch (type) {
                    case KcHeaderView.TYPE_CLICK_LEFT:
                        onFinish();
                        break;
                    case KcHeaderView.TYPE_CLICK_RIGHR:
                        break;
                }
            }
        });
        initPageListView(1);
        MAPP.mRunStatePage = new KcNoneListener() {
            @Override
            public void onMessage() {
                if (makeBUsage()){
                    onLoadData();
                }
            }
        };
        mBUsage = new List[2];
    }
    void onLoadData(){
//        MSKIN.delDbsAllItem(MBAPP.MEMORY_FREE_TYPE, MBAPP.MEMORY_OBJECT);
//        MSKIN.delDbsAllItem(MBAPP.MEMORY_FREE_TYPE, MBAPP.MEMORY_TOP_LIST);
//        List<Object> lists;
//        MLOG(String.format("appListA length %s ", "AAAAAAAAAAAA"));
//        lists = new ArrayList<>();
        BUsage bUsage = new BUsage();
        String text = MDBS.getFreeText(0, "POWER_ON_TICK");
        if (!MAPI.isEmpty(text)) {
            bUsage.LastUsed = Long.parseLong(text);
        }
//        Object object = MAPP.getMemoryFree(FreeType.POWER_ON_TICK);
//        if (object instanceof Long) {
//            bUsage.LastUsed = (long)object;
//        }
        bUsage.PackageName = "f";
//        lists.add(bUsage);

//        lists.add(MAPP.getMemoryFree(FreeType.RUN_APP_LIST));
        mBUsage[0] = MDBS.getBUsage(0);
        Collections.sort(mBUsage[0], new Comparator<BUsage>() {
            public int compare(BUsage info1, BUsage info2) {
                return (int) (info2.LastUsed - info1.LastUsed);  // 降序
            }
        });


        mBUsage[1] = MDBS.getBUsage(1);
        Collections.sort(mBUsage[1], new Comparator<BUsage>() {
            public int compare(BUsage info1, BUsage info2) {
                return (int) (info2.LastUsed - info1.LastUsed);  // 降序
            }
        });
//        lists.addAll(top);
//        setListView(0, (List)mBUsage[0]);
//        setListView(1, (List)mBUsage[1]);
    }

    @Override
    public void onInitData(){                                                                       // onInitView结束，开始加载数据
        onLoadData();
    }
    @Override
    public void onFinish(){                         // 使用者选择性继承，用户按了后退键，不继承就直接关闭了
        MAPP.mRunStatePage = null;
        setClose();
    }




    public boolean makeBUsage() {
        return false;
//        List<BUsage> lists;
//
//        Context context = MRAM.mContext;
////        if (mBUsage == null){
////            mBUsage = new ArrayList<>();
////            long tick = System.currentTimeMillis();
////            MDBS.setFreeText(0, "POWER_ON_TICK", String.format("%s", tick));
////        }
//        boolean different = false;
////        String currentApp = "CurrentNULL";
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
//            UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
//            long time = System.currentTimeMillis();
//            List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - (24 * 60 * 60 * 1000), time);
////            MLOG( "Current App A appList: " + appList);
//            if (appList != null && appList.size() > 0) {
//                int length = appList.size();
//                lists = new ArrayList<>();
//                for (int index = 0; index < length; index++){
//                    UsageStats usageStats = appList.get(index);
//                    long lastTimeUsed = usageStats.getLastTimeUsed();
//                    if (lastTimeUsed != 0) {
//                        BUsage bUsage = new BUsage();
//                        bUsage.LastUsed = lastTimeUsed;
//                        bUsage.FirstTime = usageStats.getFirstTimeStamp();
//                        bUsage.LastTime = usageStats.getLastTimeStamp();
//                        bUsage.PackageName = usageStats.getPackageName();
//                        lists.add(bUsage);
//                    }
//                }
//                Collections.sort(lists, new Comparator<BUsage>() {
//                    public int compare(BUsage info1, BUsage info2) {
//                        return (int) (info2.LastUsed - info1.LastUsed);  // 降序
//                    }
//                });
//                length = lists.size();
//
//                if (length != lists.size()){
//                    different = true;
//                }else {
//                    for (int index = 0; index < length; index++) {
//                        if (!lists.get(index).PackageName.equals(lists.get(index).PackageName)){  // 包名的位置已经不同
//                            different = true;
////                            MLOG(String.format("makeBUsageAAy %s", index, index));
//                            break;
//                        }
//                    }
//                }
//                if (different){                                 // 不同了，重新写入列表
//                    MDBS.setBUsage(1, lists);
//                    lists = new ArrayList<>();
//                    lists.addAll(lists);
//                    MLOG("makeBUsageAA RUN_APP_LIST 改变");
//
//                    if (length > 0) {
//                        Object object1 = MAPP.getMemoryFree(FreeType.WRITE_TOP_TICK);
//                        if (object1 instanceof Long){               // 已经有记忆了
//                            long topId = (Long) object1;
//                            length = lists.size();
//                            MLOG(String.format("makeBUsageAA1 %s %s", length, topId));
//                            for (int index = 0; index < length; index++) {
//                                if (lists.get(index).LastUsed > topId) {     // 比上次的时间新
//                                    if (index == 0){                        // 只是最顶层
//                                        Object object2 = MSKIN.getDbsItem(MEMORY_FREE_TYPE, MEMORY_TOP_LIST, String.format("%s", topId));
//                                        if (object2 instanceof BUsage) {
//                                            BUsage bUsage = (BUsage) object2;
//                                            MLOG(String.format("makeBUsageAA9 %s %s %s", bUsage.PackageName, lists.get(index).PackageName, lists.get(index).LastUsed));
//                                            if (bUsage.PackageName.equals(lists.get(index).PackageName)){   // 顶层不变
//                                                MLOG(String.format("makeBUsageAA2 %s %s %s", index, lists.get(index).LastUsed, lists.get(index).PackageName));
//                                                continue;
//                                            }
//                                        }else {
//                                            MLOG(String.format("makeBUsageAA4 %s %s %s", index, lists.get(index).LastUsed, lists.get(index).PackageName));
//                                        }
//
//                                    }
//                                    MLOG(String.format("makeBUsageAA3 %s %s %s", index, lists.get(index).LastUsed, lists.get(index).PackageName));
//                                    MAPP.setMemoryTopList(lists.get(index));    // 都需要记录下来
//                                }
//                            }
//                        }else {                                     // 还没有WRITE_TOP_TICK记忆
//                            MAPP.setMemoryTopList(lists.get(0));    // 最顶的就是最新的
//                        }
//                    }
//                }
//            }
//        } else {
//            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//            List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
//            BUsage bUsage = new BUsage();
//            bUsage.LastUsed = System.currentTimeMillis();
//            bUsage.PackageName = tasks.get(0).processName;
//            MAPP.setMemoryFree(FreeType.RUN_TOP_APP, bUsage);
////            currentApp = tasks.get(0).processName;
////            MLOG( "Current App B in foreground is: " + bUsage.PackageName);
//        }
//        return different;
    }



    public static int[] item_run_state = new int[]{      //  本地录音作品
            R.layout.item_run_state, 2,
            R.id.tvNameRun, R.id.tvTimeRun,
    };
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // KcListView的全部处理，放在页面的最后位置统一处理 ///////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    private void initListView(int tab, KcListView kcListView) {
        mKcListView[tab] = kcListView;
        mKcListView[tab].initView(null, item_run_state, null, new KcListListener() {
            @Override
            public int onMessage(int type, int tab, Object object) {
                return 0;
            }
            @Override
            public int onBindItemHolder(boolean skipImage, int tab, int position, final KcListHolder holder) {
                Object object = getListView(tab, position);
//                MLOG(String.format("onBindItemA %s %s ", position, object));
//                SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
//                if (position == 0 && object instanceof BUsage){
//                    BUsage bUsage = (BUsage)object;
//                    MSKIN.setText("唱销    打开时间", holder.mView[0]);
//                    MSKIN.setText(sdf.format(bUsage.LastUsed), holder.mView[1]);
//                }else if (position == 1 && object instanceof List){
//                    List<BUsage> lists = (List)MAPP.getMemoryFree(FreeType.RUN_APP_LIST);
//                    int length = lists.size();
//                    MLOG(String.format("appListAAA length %s ", length));
//                    StringBuffer stringBuffer = new StringBuffer();
//                    for (int index = 0; index < length; index++){
//                        BUsage bUsage = lists.get(index);
//                        String text = String.format("%s(%s)%s\n", bUsage.PackageName, sdf.format(bUsage.LastUsed), sdf.format(bUsage.FirstTime));
//                        stringBuffer.append(text);
//                    }
//                    MSKIN.setText(stringBuffer.toString(), holder.mView[0]);
//                }else  if (object instanceof BUsage){
//                    BUsage bUsage = (BUsage)object;
//                    MSKIN.setText(bUsage.PackageName, holder.mView[0]);
//                    MSKIN.setText(sdf.format(bUsage.LastUsed), holder.mView[1]);
//                }
                return 0;
            }
        });
        // (d)列表最后更新日期时间 (n)下次更新日期时间 (c)当前数量 (q)列表最大的数量
        mKcListView[tab].setStatus(false, false, "", getString(R.string.no_record_works), "");
        mKcListView[tab].setTabNumber(tab);
    }

    private void initPageListView(int tabQty) {
        mKcListView = new KcListView[tabQty];
        if (tabQty == 1) {
            mKcListView[0] = (KcListView) findViewById(R.id.klvSimpleList);
            mKcListView[0].setVisibility(View.VISIBLE);
            initListView(0, mKcListView[0]);
            return;
        }
    }
}
